package com.y2w.gulimall.ware.listener;

import com.rabbitmq.client.Channel;
import com.y2w.common.to.mq.OrderTo;
import com.y2w.common.to.mq.StockLockedTo;
import com.y2w.gulimall.ware.service.WareSkuService;
import com.y2w.gulimall.ware.vo.OrderVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues ="stock.release.stock.queue" )
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    /**
     * 库存自动解锁
     * 下单成功,库存锁定成功,接下来的业务调用失败，导致订单回滚，之前锁定的库存就是自动解锁
     * 锁库存失败
     * @param to
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException{
        System.out.println("收到解锁库存的信息");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handleOrderClosedRelease(OrderTo to, Message message, Channel channel) throws IOException{
        System.out.println("收到订单关闭的信息，准备解锁库存");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

}
